import { useState, useEffect } from "react";
import modelApi from "@/models/model";
import showToast from "@/utils/message";
function useModelList() {
  const page = 1;
  const pageSize = 99;
  const [modeData, setModeData] = useState([]);
  const getModelList = async (firstId, secondId) => {
    const { code, data } = await modelApi.list(
      firstId,
      secondId,
      page,
      pageSize
    );
    if (code == 200) {
      const list = data?.item_data || [];
      if (list?.length) {
        list.forEach((ele) => {
          ele.content = JSON.parse(ele.download);
          ele.id = ele?.content[0]?.model_id || ele.title + "_123";
        });
        setModeData((modeList) => [...modeList, ...list]);
      }
    } else {
      setModeData([]);
    }
  };

  useEffect(() => {
    async function getCategoriesList() {
      const { data, code } = await modelApi.categories();
      if (code == 200) {
        if (data?.first_category?.length) {
          const categoriesList = data.first_category.filter((item) => {
            const dateType = JSON.parse(item.attributes)?.datatype;
            return dateType == "models";
          });
          if (categoriesList?.length) {
            const tabList = categoriesList[0].categories.map((item) => {
              return {
                key: item.category_id,
                label: item.title,
                id: item.category_id,
              };
            });
            getModelList(categoriesList[0].id, tabList[0].key);
          } else {
            showToast("error", "获取模型类型失败");
          }
        } else {
          showToast("error", "获取模型类型失败");
        }
      } else {
        showToast("error", "获取模型类型失败");
      }
    }
    getCategoriesList();
  }, []);
  return modeData;
}
export default useModelList;
